package com.kaibes.orm.core.plus;

import java.lang.reflect.Field;
import java.util.Map;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.orm.core.annotation.Column;
import com.kaibes.orm.curd.UpdateBuilder;

public class UpdateBuilderPlus extends UpdateBuilder {

    public UpdateBuilderPlus setData(final Object data, String...ignores) {
        Field[] fieds = data.getClass().getDeclaredFields();
        for (Field field : fieds) {
            for (String ignore : ignores) {
                if (field.getName().equals(ignore)) {
                    continue;
                }
            }
            
            if (field.isAnnotationPresent(Column.class)) {
                String name = field.getDeclaredAnnotation(Column.class).value();
                if (!name.isEmpty()) {
                    field.setAccessible(true);
                    try {
                        Object value = field.get(data);
                        if (value != null) {
                            setValue(name, value);
                        }
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            } else {
                String name = field.getName();
                name = StringUtils.humpToLine(name);
                field.setAccessible(true);
                try {
                    Object value = field.get(data);
                    if (value != null) {
                        setValue(name, value);
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return this;
    }
    
    public UpdateBuilderPlus setData(Map<String, Object> data) {
        data.forEach((t, u)->setValue(StringUtils.humpToLine(t), u));
        return this;
    }
    
    public static UpdateBuilderPlus newBuilder() {
        return new UpdateBuilderPlus();
    }
}
